package com.lkd.business;

import com.lkd.annotations.ProcessType;
import com.lkd.common.VMSystem;
import com.lkd.contract.VmStatusContract;
import com.lkd.feignService.VMService;
import com.lkd.http.viewModel.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.viewmodel.VendingMachineViewModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@ProcessType(value = "vmStatus")
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;
    @Override
    public void process(String jsonMsg) throws IOException {
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract==null||vmStatusContract.getStatusInfo()==null||vmStatusContract.getStatusInfo().size()<=0)
            return;
        //如果为非正常状态，则创建维修工单
        if (vmStatusContract.getStatusInfo().stream().anyMatch(s-> !s.isStatus())){
            try {
                //根据售货机编号查询售货机
                VendingMachineViewModel vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                //查询最少工单量用户
                Integer userId = taskService.getLeastUser(vmInfo.getRegionId(), true);
                //创建工单对象
                TaskViewModel taskViewModel = new TaskViewModel();
                taskViewModel.setUserId(userId);
                taskViewModel.setInnerCode(vmStatusContract.getInnerCode()); //售货机id
                taskViewModel.setDesc("自动维修工单");
                taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR); //维修工单
                taskViewModel.setCreateType(0);
                taskService.createTask(taskViewModel);
            }catch (Exception e){
                log.error("创建维修工单失败 msg is："+jsonMsg);
            }
        }
    }
}
